package net.xdclass.listener;

import com.alibaba.nacos.common.utils.MapUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.message.NativeOrderRequestMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @description todo 支付结果通知监听 需要重试5次，失败直接丢弃
 * @since 2023-09-02 23:02
 */
@Slf4j
@Component
@RabbitListener(queuesToDeclare = {@Queue("pay.result.notify.queue")})
public class PayResultNotifyListener {

    @Autowired
    private RestTemplate restTemplate;

    /**
     *
     * 异步通知业务订单支付结果
     *
     * @param eventMessage
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void payResultNotifyHandler(NativeOrderRequestMessage eventMessage, Message message, Channel channel) throws IOException {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        String notifyUrl = eventMessage.getNotifyUrl();
        if (StringUtils.isEmpty(notifyUrl)) {
            channel.basicAck(deliveryTag, false);
            return;
        }
        Map<String, Object> payResult = new HashMap<>();
        payResult.put("outTradeNo", eventMessage.getOutTradeNo());
        payResult.put("mchid", eventMessage.getMchid());
        payResult.put("orderStatus", eventMessage.getOrderStatus());
        payResult.put("attach", eventMessage.getAttach());

        log.info("请求地址: {}, 请求参数: {}", notifyUrl, payResult);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(payResult, headers);
        ResponseEntity<Map> responseEntity = restTemplate.postForEntity(notifyUrl, mapHttpEntity, Map.class);

        if (responseEntity.getBody() == null) {
            log.error("通知失败: {}", eventMessage);
            throw new RuntimeException("订单通知失败");
        }

        Object code = responseEntity.getBody().get("code");
        if (code != null && (Integer) code == 0) {
            log.info("通知成功,响应参数: {}", responseEntity.getStatusCode());

        } else {
            log.error("通知失败: {}", eventMessage);
            // channel.basicNack(deliveryTag, false, true);
            throw new RuntimeException("订单通知失败");
        }



    }
}
